package leetcode.code1910;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String removeOccurrences(String s, String part) {
		if (s.length() < part.length()) {
			return s;
		}
		char[] chars2 = part.toCharArray();
		int len2 = chars2.length;
		int[] p = new int[len2];
		// p中m位置记录数值n,表示[0,n-1]的字符串同[m-n+1,m]字符串相同
		for (int i = 1, j = 0; i < len2 && j < len2; i++) {
			while (j > 0 && chars2[j] != chars2[i]) {
				j = p[j - 1];
			}
			if (chars2[i] == chars2[j]) {
				j++;
			}
			p[i] = j;
		}
		return this.remove(s, part, p);
	}

	public String remove(String s, String part, int[] p) {
		if (s.length() < part.length()) {
			return s;
		}
		char[] chars1 = s.toCharArray();
		char[] chars2 = part.toCharArray();
		int len1 = chars1.length;
		int len2 = chars2.length;
		int start = -1;
		for (int i = 0, j = 0; i < len1 && j < len2; i++) {
			while (j > 0 && chars2[j] != chars1[i]) {
				j = p[j - 1];
			}
			if (chars2[j] == chars1[i]) {
				j++;
			}
			if (j == len2) {
				start = i - j + 1;// i-(j-1)
				break;
			}
		}
		if (start == -1) {
			return s;
		}
		char[] rest = new char[len1 - len2];
		int prest = 0;
		for (int i = 0; i < start; i++) {
			rest[prest++] = chars1[i];
		}
		for (int i = start + len2; i < len1; i++) {
			rest[prest++] = chars1[i];
		}
		return this.remove(new String(rest), part, p);
	}

	@Override
	public void debug4() {
		H.compare("dab", this.removeOccurrences("daabcbaabcbc", "aaab"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
